import React, { Component } from 'react'
import { Table, Modal, Button, message, Select, Card, Form, Input } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'

import { reqUserList, reqUserDel, reqUserAdd, reqUserUpdate } from '../../api'

import LinkButton from '../../components/link-button'
import { options } from 'less'

export default class User extends Component {
  state = {
    isShowAddOrUpdate: 0,
    isShowDel: false,
    users: [],
    roles: [],
    options: [], // 角色列表
    user: [], //用作修改用户时绑定数据
  }
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name
      return pre
    }, {})
    this.roleNames = roleNames
  }

  initColumn = () => {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username'
      }, {
        title: '邮箱',
        dataIndex: 'email'
      }, {
        title: '电话',
        dataIndex: 'phone'
      }, {
        title: '注册时间',
        dataIndex: 'create_time'
      }, {
        title: '所属角色',
        dataIndex: 'role_id',
        render: (role_id) => this.roleNames[role_id]
      }, {
        title: '操作',
        render: (user) => {
          return (
            <span>
              <LinkButton onClick={() => this.updateuser(user)}>修改</LinkButton>
              <LinkButton onClick={() => this.delUser(user._id)}>删除</LinkButton>
            </span>
          )
        }
      }
    ]
  }

  getUsers = async () => {
    const { data: result } = await reqUserList()
    if (result.status === 0) {
      const { users, roles } = result.data
      this.initRoleNames(roles)

      let options = []
      roles.forEach(role => options.push({ value: role._id, label: role.name }))
      this.setState({ users, roles, options })
    }
  }

  addUser = async (values) => {
    const { data: result } = await reqUserAdd(values)
    if (result.status === 0) {
      message.success('用户添加成功')
      this.getUsers()
    } else {
      message.error('用户添加失败')
    }
  }

  updateuser = (user) => {
    this.setState({ isShowAddOrUpdate: 2, user })
  }

  updateUser = async (values) => {
    const { data: result } = await reqUserUpdate(values)
    console.log(result);
    if (result.status === 0) {
      message.success('用户信息修改成功')
      this.getUsers()
    } else {
      message.error('用户信息修改失败')
    }
  }

  delUser = async (userId) => {
    Modal.confirm({
      title: '删除用户',
      icon: <ExclamationCircleOutlined />,
      content: '是否删除该用户',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const { data: result } = await reqUserDel(userId)
        if (result.status === 0) {
          message.success('删除用户成功')
          this.getUsers()
        } else {
          message.error('删除用户失败')
        }
      }
    });

  }

  AddOrUpdateUser = async () => {
    // console.log(this.formRef);
    const { isShowAddOrUpdate } = this.state

    this.formRef.current.validateFields()
      .then(values => {
        if (isShowAddOrUpdate === 1) { // 新增用户
          this.addUser(values)
        } else if (isShowAddOrUpdate === 2) { // 更新用户
          this.updateUser(values)
        }
        this.formRef.current.resetFields()
      })
      .catch(info => {
        let error = info.errorFields
        console.log(error);
        error.forEach(item => {
          message.error(item.errors)
        })
      });

  }

  componentWillMount() {
    this.initColumn()
  }

  componentDidMount() {
    this.getUsers()
  }

  formRef = React.createRef();

  render() {
    const title = <Button type="primary" onClick={() => this.setState({ isShowAddOrUpdate: 1 })}>创建用户</Button>

    const { users, isShowAddOrUpdate, options, user } = this.state

    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 16 }
    }

    return (
      <Card title={title}>
        <Table
          bordered
          rowKey="_id"
          columns={this.columns}
          dataSource={users}
          pagination={{ defaultPageSize: 5 }}
        />
        <Modal
          title={isShowAddOrUpdate === 1 ? '创建用户' : '修改用户信息'}
          visible={isShowAddOrUpdate}
          onOk={this.AddOrUpdateUser}
          onCancel={() => this.setState({ isShowAddOrUpdate: false })}
        >
          <Form
            {...formItemLayout}
            ref={this.formRef}
            initialValues={{
              username: user.username,
              password: user.password,
              email: user.email,
              phone: user.phone,
              role_id: user.role_id
            }}
          >
            <Form.Item label="用户名" name="username">
              <Input placeholder="请输入用户名"/>
            </Form.Item>
            <Form.Item label="密码" name="password">
              <Input type='password' placeholder="请输入密码" />
            </Form.Item>
            <Form.Item label="邮箱" name="email">
              <Input placeholder="请输入邮箱" />
            </Form.Item>
            <Form.Item label="电话" name="phone">
              <Input placeholder="请输入电话" />
            </Form.Item>
            <Form.Item label="角色" name="role_id">
              <Select placeholder="请选择角色" options={options}></Select>
            </Form.Item>
          </Form>
        </Modal>
      </Card >
    )
  }
}